package com.wz.db;

import com.wz.bean.SendedMsg;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class SmsProvider extends ContentProvider{

	private static final String AUTHORITY = "com.wz.SmsProvider";
	public static final Uri URI_SMS_ALL = Uri.parse("content://"+AUTHORITY+"/sms");
	private static UriMatcher matcher;
	private static final int SMS_ALL = 0;
	private static final int SMS_ONE = 1;
	static{
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI(AUTHORITY, "sms", SMS_ALL);
		matcher.addURI(AUTHORITY, "sms/#", SMS_ONE);
	}
	
	private SQLiteOpenHelper mhelper;
	private SQLiteDatabase mdb;
	
	@Override
	public boolean onCreate() {
	    mhelper = SmsDbOpenHelper.getInstance(this.getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		int match = matcher.match(uri);
		if(match == SMS_ALL){
			
		}else if(match == SMS_ONE){
			long id = ContentUris.parseId(uri);
			selection = "_id = ?";
			selectionArgs = new String[]{String.valueOf(id)};
		}else{
			throw new IllegalArgumentException("Uri 不匹配!");
		}
		mdb = mhelper.getReadableDatabase();
		Cursor cursor = mdb.query(SendedMsg.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
		
		cursor.setNotificationUri(this.getContext().getContentResolver(), URI_SMS_ALL);
		
		return cursor;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int match = matcher.match(uri);
		if(match != SMS_ALL){
			throw new IllegalArgumentException("Uri 不匹配");
		}
		mdb = mhelper.getWritableDatabase();
		long rowid = mdb.insert(SendedMsg.TABLE_NAME, null, values);
		if(rowid >= 0){
			notifyDataSetChanged();
			return ContentUris.withAppendedId(uri, rowid);
		}
		
		return null;
	}

	private void notifyDataSetChanged() {
		this.getContext().getContentResolver().notifyChange(URI_SMS_ALL, null);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		return 0;
	}

}
